package fun.sanguo.service.interact.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import fun.sanguo.mapper.interact.InteractPersonageLikeMapper;
import fun.sanguo.model.dto.DataInfo;
import fun.sanguo.model.dto.PageInsert;
import fun.sanguo.model.dto.PageUpdate;
import fun.sanguo.model.dto.interact.InteractPersonageLikeInsert;
import fun.sanguo.model.dto.interact.InteractPersonageLikeResult;
import fun.sanguo.model.dto.interact.InteractPersonageLikeUpdate;
import fun.sanguo.model.entity.interact.InteractPersonageLikeEntity;
import fun.sanguo.model.enums.ResEnums;
import fun.sanguo.service.interact.InteractPersonageLikeService;
import fun.sanguo.utils.DateUtils;
import fun.sanguo.utils.IdUtils;
import fun.sanguo.utils.exception.ArtificialException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 互动-人物喜欢记录 Service实现类
 *
 * @author ZYP
 * @date 2023-10-13
 */
@Service
public class InteractPersonageLikeServiceImpl implements InteractPersonageLikeService {

    @Resource
    private InteractPersonageLikeMapper interactPersonageLikeMapper;

    /**
     * 新增
     *
     * @param pageInsert
     * @param userId
     * @param userIp
     * @return
     * @throws ArtificialException
     */
    @Override
    public DataInfo<InteractPersonageLikeResult> insert(PageInsert<InteractPersonageLikeInsert> pageInsert, String userId, String userIp) throws ArtificialException {
        // 新增参数
        InteractPersonageLikeEntity interactPersonageLikeEntity = new InteractPersonageLikeEntity();
        // 转换新增参数
        try {
            // 接收参数
            InteractPersonageLikeInsert interactPersonageLikeInsert = new ObjectMapper().convertValue(pageInsert.getParam(), InteractPersonageLikeInsert.class);
            // 赋值到实体类
            BeanUtils.copyProperties(interactPersonageLikeInsert, interactPersonageLikeEntity);
            interactPersonageLikeEntity.setUserId(userId);
            interactPersonageLikeEntity.setUserIp(userIp);
            interactPersonageLikeEntity.setLikeTime(new Date());
            // 其他参数赋值
            interactPersonageLikeEntity.setId(String.valueOf(new IdUtils().nextId()));
            interactPersonageLikeEntity.setCreateBy("system");
            interactPersonageLikeEntity.setCreateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageLikeEntity.setUpdateBy("system");
            interactPersonageLikeEntity.setUpdateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageLikeEntity.setVersion(1);
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_PARAM.getCode(), ResEnums.ERR_PARAM.getMsg(), e);
        }
        // 新增数据并得到操作结果
        try {
            // 新增
            int amount = interactPersonageLikeMapper.insert(interactPersonageLikeEntity);
            // 查询指定人物的喜欢数量、指定用户是否喜欢
            InteractPersonageLikeResult result = getSummaryByUserPersonage(userId, interactPersonageLikeEntity.getPersonageId());
            // 增加操作结果
            result.setResult(amount > 0);
            // 返回操作结果
            return new DataInfo<>(result);
        } catch (ArtificialException ae) {
            throw ae;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 删除
     *
     * @param pageUpdate
     * @param userId
     * @return
     * @throws ArtificialException
     */
    @Override
    public DataInfo<InteractPersonageLikeResult> delete(PageUpdate<InteractPersonageLikeUpdate> pageUpdate, String userId) throws ArtificialException {
        // 删除参数
        InteractPersonageLikeEntity interactPersonageLikeEntity = new InteractPersonageLikeEntity();
        // 转换删除参数
        try {
            // 接收参数
            InteractPersonageLikeUpdate interactPersonageLikeUpdate = new ObjectMapper().convertValue(pageUpdate.getParam(), InteractPersonageLikeUpdate.class);
            // 赋值到实体类
            interactPersonageLikeEntity.setId(interactPersonageLikeUpdate.getId());
            // 其他参数赋值
            interactPersonageLikeEntity.setUpdateBy("system");
            interactPersonageLikeEntity.setUpdateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_PARAM.getCode(), ResEnums.ERR_PARAM.getMsg(), e);
        }
        // 删除数据并得到操作结果
        try {
            // 查询记录信息
            InteractPersonageLikeEntity record = interactPersonageLikeMapper.getById(interactPersonageLikeEntity.getId());
            // 非当前登陆用户则报错
            if (record == null || StringUtils.isEmpty(record.getUserId()) || !record.getUserId().equals(userId)) {
                throw new ArtificialException(ResEnums.ERR_USER_NOTAllOW.getCode(), ResEnums.ERR_USER_NOTAllOW.getMsg(), null);
            }
            // 删除
            int amount = interactPersonageLikeMapper.delete(interactPersonageLikeEntity);
            // 查询指定人物的喜欢数量、指定用户是否喜欢
            InteractPersonageLikeResult result = getSummaryByUserPersonage(userId, record.getPersonageId());
            // 增加操作结果
            result.setResult(amount > 0);
            // 返回操作结果
            return new DataInfo<>(result);
        } catch (ArtificialException ae) {
            throw ae;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 查询指定人物的喜欢数量及是否被指定用户喜欢
     *
     * @param userId
     * @param personageId
     * @return
     * @throws ArtificialException
     */
    @Override
    public InteractPersonageLikeResult getSummaryByUserPersonage(String userId, String personageId) throws ArtificialException {
        try {
            // 根据用户与人物查询记录
            InteractPersonageLikeEntity interactPersonageLikeEntity = interactPersonageLikeMapper.getByUserPersonage(userId, personageId);
            // 查询指定人物的喜欢数量
            int amount = interactPersonageLikeMapper.getSummaryByPersonage(personageId);
            // 封装返回结果
            InteractPersonageLikeResult interactPersonageLikeResult = new InteractPersonageLikeResult();
            if (interactPersonageLikeEntity != null) {
                interactPersonageLikeResult.setInteractId(interactPersonageLikeEntity.getId());
            }
            interactPersonageLikeResult.setAmount(amount);
            // 返回查询结果
            return interactPersonageLikeResult;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 查询所有人物的喜欢数量及是否被指定用户喜欢
     *
     * @param userId
     * @return
     * @throws ArtificialException
     */
    @Override
    public Map<String, InteractPersonageLikeResult> getSummaryByUser(String userId) throws ArtificialException {
        try {
            // 根据用户查询记录
            List<InteractPersonageLikeEntity> interactPersonageLikeEntityList = interactPersonageLikeMapper.getByUser(userId);
            // 查询所有人物的喜欢数量
            List<JSONObject> summaryList = interactPersonageLikeMapper.getSummary();
            // 返回结果
            Map<String, InteractPersonageLikeResult> interactPersonageLikeResultMap = new HashMap<>();
            // 先遍历统计结果，封装所有人物
            summaryList.forEach(summary -> {
                InteractPersonageLikeResult interactPersonageLikeResult = new InteractPersonageLikeResult();
                interactPersonageLikeResult.setAmount(summary.getLong("AMOUNT"));
                interactPersonageLikeResultMap.put(summary.getString("PERSONAGE_ID"), interactPersonageLikeResult);
            });
            // 遍历用户喜欢列表
            interactPersonageLikeEntityList.forEach(interactPersonageLikeEntity -> {
                interactPersonageLikeResultMap.get(interactPersonageLikeEntity.getPersonageId()).setInteractId(interactPersonageLikeEntity.getId());
            });
            // 返回查询结果
            return interactPersonageLikeResultMap;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }
}
